//
//  HYPictureView.swift
//  weibo-01
//
//  Created by 源 何 on 16/9/28.
//  Copyright © 2016年 何源. All rights reserved.
//

import UIKit

private let cellID = "HYPictureViewID"
class HYPictureView: UICollectionView {
    
    var pictureInfos: [HYStatusPictureInfo]? {
        didSet{
            testLabel.text = "\(pictureInfos?.count ?? 0)张"
            //刷新视图 数据一旦发生了修改之后就应该reloadData 配图视图才会复用
            reloadData()
        }
    }
    
    override func awakeFromNib() {
        //显示数据 设置数据源对象
        self.dataSource = self
        
//        self.backgroundColor = randomColor()
        
        self.addSubview(testLabel)
        
        testLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        register(HYPictureCell.self, forCellWithReuseIdentifier: cellID)
        
    }

    //测试label
    private lazy var testLabel: UILabel = {
        let l = UILabel(title: "", textColor: UIColor.black, fontSize: 30)
        return l
    } ()
}

extension HYPictureView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfos?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! HYPictureCell
//        cell.backgroundColor = randomColor()
        cell.pictureInfo = pictureInfos![indexPath.item]
        return cell
    }
}

//一个文件中可以写多个类
class HYPictureCell: UICollectionViewCell {
    var pictureInfo: HYStatusPictureInfo? {
        didSet{
            let url = URL(string: pictureInfo?.thumbnail_pic ?? "")
            imageView.sd_setImage(with: url)
        }
    }
    
    //添加一个iv
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加子视图
        self.contentView.addSubview(imageView)
        //设置约束
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView.snp.edges)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        
        //设置图片显示样式
        //iv.contentMode = .scaleToFill 图片比例失真
        //iv.contentMode = .scaleAspectFit 造成图片视图显示不满
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
}
